package com.engc.common;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.StopWatch;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class SystemInterceptor extends HandlerInterceptorAdapter {

	private Log log = LogFactory.getLog(SystemInterceptor.class);

	boolean usePerformance = true;

	ThreadLocal<Object> stopWatchLocal = new ThreadLocal<Object>();

	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

		if (usePerformance) {
			StopWatch stopWatch = new StopWatch(handler.toString());
			stopWatchLocal.set(stopWatch);
			stopWatch.start(handler.toString());
		}

		return true;
	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		
		System.out.println("ok..");
	}

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		if (usePerformance) {
			StopWatch stopWatch = (StopWatch) stopWatchLocal.get();
			stopWatch.stop();
			String currentPath = request.getRequestURI();
			String queryString = request.getQueryString();
			queryString = queryString == null ? "" : "?" + queryString;
			log.info("access url path:" + currentPath + queryString + " |time:" + stopWatch.getTotalTimeMillis());
			
			
			stopWatchLocal.set(null);
		}
	}

}
